<?php

declare(strict_types=1);

namespace Tools\Api\Hanzi;

use Tools\Net\HTTPSProxy;

/**
 * @todo headers problem
 *
 * Session simulation for the api about the hanzi company
 *
 * Class SessionSimulation
 * @package Tools\Api\Hanzi
 */
class SessionSimulation
{
    /**
     * Url data load handle.
     */
    use UrlDataLoad;

    /**
     * @var string $token
     */
    public $token;

    /**
     * @var bool $status
     */
    public $status;

    /**
     * @var bool $isTest
     */
    protected $isTest = true;

    /**
     * @var int $userId
     */
    protected $userId = 1;

    /**
     * @var array $clientData
     */
    protected $clientData = [];

    /**
     * SessionSimulation constructor.
     * @param int $userId
     */
    public function __construct(int $userId)
    {
        $this->userId = $userId;
    }

    /**
     * Get Api token.
     *
     * @throws \Exception
     */
    public function getApiToken()
    {
        $obj = HTTPSProxy::handle($this->domain . $this->urlList['initialize']);

        if ($obj->result == false) throw new \Exception('Initialize token failure!');

        $this->token = $obj->token;
    }

    /**
     * handle status
     *
     * @throws \Exception
     */
    public function checkStatus()
    {
        $result = HTTPSProxy::handle(
            $this->getSendUrlBuildToken('status'),
            [],
            'GET',
            [],
            [
                'Authorization' => $this->token,
                'X-ISAPI' => 1,
                'X-VERSION' => 1.1,
            ]
        );

        if (isset($result->status) && $result->status === true) {
            $this->status = true;

            return ;
        }

        throw new \Exception($result->error_msg, $result->error_code);
    }

    /**
     * Initialize Object.
     *
     * @throws \Exception
     */
    public function initialize()
    {
        $this->getApiToken();
        $this->checkStatus();
    }

    /**
     * Build request url
     *
     * @param $parameter
     *
     * @return string
     */
    protected function urlBuilder($parameter)
    {
        $url = $parameter;

        if ($this->isTest) {
            $url .= '?usertest=' . $this->userId;
        }

        return $url;
    }

    /**
     * Build token to url
     *
     * @param $action
     *
     * @return string
     */
    protected function getSendUrlBuildToken($action)
    {
        return $this->domain . $this->urlList[$action] . "?token={$this->token}";
    }
}
